import { Button, Form, Input, Select, Modal, Alert } from 'antd';
import _ from 'lodash';
import * as React from 'react';

const FormItem = Form.Item;
const Option = Select.Option;

class NewRuntimeForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      submiting: false
    };
  }

  doSubmit(evt) {
    evt.preventDefault();
    const { form: { getFieldsValue }, onSubmit, groupId } = this.props;
    this.setState({ submiting: true });
    const params = getFieldsValue();
    params.groupId = groupId;
    if (params.copyFrom === 'none') {
      params.copyFrom = undefined;
    }
    return onSubmit(params)
      .then(() => this.setState({ submiting: false }));
  }

  render() {
    const { form: { getFieldProps }, runtimes } = this.props;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    };

    return (
      <Form horizontal onSubmit={::this.doSubmit}>
        <FormItem label='名称：' required {...formItemLayout}>
          <Input type='text' {...getFieldProps('name')}/>
        </FormItem>
        {_.isEmpty(runtimes) ? undefined : (
          <FormItem label='从所选环境复制：' {...formItemLayout}
            help={<Alert message='以复制方式从目标环境创建一个新环境，会复制目标环境中所有的运行单元。可在复制创建后修改分支或增减运行单元。' type='info'/>}>
            <Select {...getFieldProps('copyFrom', { initialValue: 'none' })}>
              <Option value='none'>不复制</Option>
              {runtimes.map(({ id, name }) => <Option value={id} key={id}>{name}</Option>)}
            </Select>
          </FormItem>
        )}
        <FormItem label=' ' {...formItemLayout}>
          <Button htmlType='submit' type='primary' loading={this.state.submiting}>创建</Button>
        </FormItem>
      </Form>
    );
  }
}
NewRuntimeForm = Form.create()(NewRuntimeForm);

class NewRuntimeModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false
    };
  }

  onSubmit(newRuntimeData) {
    return this.props.onRuntimeCreate(newRuntimeData)
      .then(() => {
        this.close();
      });
  }

  close() {
    this.refs.form.resetFields();
    this.setState({ show: false });
  }

  show() {
    this.setState({ show: true });
  }

  render() {
    return (
      <Modal title='创建运行环境'
        visible={this.state.show}
        footer={undefined}
        onCancel={::this.close}
      >
        <NewRuntimeForm ref='form' groupId={this.props.groupId} runtimes={this.props.runtimes}
          onSubmit={::this.onSubmit}/>
      </Modal>
    );
  }
}

export default NewRuntimeModal;
